package com.my.commonlibrary.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.PermissionRequest;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.my.commonlibrary.R;
import com.my.commonlibrary.base.BaseFragment;

import java.io.File;

import butterknife.Bind;
import butterknife.ButterKnife;

import static android.app.Activity.RESULT_CANCELED;
import static android.app.Activity.RESULT_OK;

/**
 * Author : Cooper
 * Time : 2016/11/4  16:03
 * Description : H5页面打开相机和相册，并且上传相片功能
 */

public class H_CameraAndPhotoAlbumFragment extends BaseFragment {


    @Bind(R.id.mWebView)
    WebView mWebView;

    private String url = "https://test.wanglibao.com/wechat/index.html#1";

    public final int PHOTO_ALBUM_REQUEST_CODE = 1000; // 客服页面获取手机图片请求code
    public final int CAMERA_REQUEST_CODE = 1001; // 客服页面获取手机图片请求code
    private ValueCallback<Uri[]> mFilePathCallbacks;
    private ValueCallback<Uri> mFilePathCallback;
    private PopupWindow mControlPop;
    private View rootView;

    @Override
    protected int getFragmentLayoutRes() {
        return R.layout.frag_camera_photo_album_layout;
    }

    @Override
    protected void initFragmentData() {
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setWebChromeClient(new MyWebChromeClient());
        mWebView.setWebViewClient(new MyWebViewClient());
        mWebView.loadUrl(url);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
        }
    }

    class MyWebChromeClient extends WebChromeClient {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            mFilePathCallbacks = filePathCallback;
            showControlPop();
            return true;
        }

        // For Android < 3.0
        public void openFileChooser(ValueCallback<Uri> valueCallback) {
            mFilePathCallback = valueCallback;
        }

        // For Android  >= 3.0
        public void openFileChooser(ValueCallback valueCallback, String acceptType) {
            mFilePathCallback = valueCallback;
        }

        //For Android  >= 4.1
        public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
            mFilePathCallback = valueCallback;
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PHOTO_ALBUM_REQUEST_CODE && resultCode == RESULT_OK) {
            if (data != null) {
                setFilePathCallback(data.getData());
            }
        } else if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            Uri uriImageData = null;
            if (data.getData() != null) {
                uriImageData = data.getData();
            } else {
                Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
                uriImageData = Uri.parse(MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), bitmap, null, null));
            }
            setFilePathCallback(uriImageData);
        } else if (resultCode == RESULT_CANCELED) {
            setFilePathCallback(null);
        }
    }

    /**
     * 设置打开相册回调
     *
     * @param uri
     */
    private void setFilePathCallback(Uri uri) {
        if (mFilePathCallback != null) {
            mFilePathCallback.onReceiveValue(uri);
            mFilePathCallback = null;
        }
        if (mFilePathCallbacks != null) {
            if (uri == null) {
                mFilePathCallbacks.onReceiveValue(null);
            } else {
                mFilePathCallbacks.onReceiveValue(new Uri[]{uri});
            }
            mFilePathCallbacks = null;
        }
    }

    /**
     * 打开手机相册
     */
    private void openPhotoAlbum() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("*/*");
        startActivityForResult(intent, PHOTO_ALBUM_REQUEST_CODE);
    }

    /**
     * 打开相机
     */
    private void openCamera() {
//        File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
//        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
//        Uri imageUri = Uri.fromFile(file);
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);//将拍取的照片保存到指定URI
        startActivityForResult(intent, CAMERA_REQUEST_CODE);
    }

    private void showControlPop() {
        if (mControlPop == null) {
            initControlPop();
        }
        mControlPop.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
    }

    private void initControlPop() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.pop_camera_photoalbum_layout, null);
        mControlPop = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, false);
        mControlPop.setContentView(view);
        TextView camera_tv = (TextView) view.findViewById(R.id.camera_tv);
        TextView photo_album_tv = (TextView) view.findViewById(R.id.photo_album_tv);
        TextView cancel_tv = (TextView) view.findViewById(R.id.cancel_tv);
        camera_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openCamera();
                mControlPop.dismiss();
            }
        });
        photo_album_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openPhotoAlbum();
                mControlPop.dismiss();
            }
        });
        cancel_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setFilePathCallback(null);
                mControlPop.dismiss();
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

}
